﻿using System.Collections.Generic;
using System.Linq;
using Heyo.Launcher.Models;
using Heyo.Launcher.Models.Data;
using HeyoUi.Models.Data.Game;
using KMCCC.Authentication;
using KMCCC.Launcher;
using KMCCC.Tools;
using Version = KMCCC.Launcher.Version;

namespace HeyoUi
{
    public static class LauncherBasic
    {
        static LauncherBasic()
        {
            JavaPaths = SystemTools.FindJava();
            KmcccCore = LauncherCore.Create(new LauncherCoreCreationOption());
            RefreshVersion();
        }

        public static void RefreshVersion()
        {
            Versions = KmcccCore.GetVersions().ToList();
            GameInfos = Versions.Select(t => new LocalGameInfo(t)).ToList();
        }
        public static LauncherCore KmcccCore { get; }

        public static List<Version> Versions { get; private set; }
        public static List<LocalGameInfo> GameInfos { get; private set; } 
        public static LocalGameInfo SelectedGame { get; set; }

        public static LaunchResult LaunchGame()
        {

            IAuthenticator authenticator =
                SettingModel.Setting.AuthMode == (int)AuthMode.Offline
                    ? (IAuthenticator) new OfflineAuthenticator(PlayerName)
                    :  SettingModel.Setting.UseCustomLoginUrl
                        ? new YggdrasilLogin(SettingModel.Setting.Email, SettingModel.Setting.Password, true,authServer:SettingModel.Setting.CustomLoginUrl+"/authserver")
                        :new YggdrasilLogin(SettingModel.Setting.Email, SettingModel.Setting.Password, true);
            
            return KmcccCore.Launch(new LaunchOptions()
            {
                Version = SelectedGame.KmcccVersion,
                Authenticator = authenticator,
                Size = new WindowSize()
                {
                    FullScreen = SettingModel.Setting.IsFullScreen,
                    Height = SettingModel.Setting.WindowH,
                    Width = SettingModel.Setting.WindowW
                },
                MaxMemory = SettingModel.Setting.MaxMemory,
            });
        }
        public static IEnumerable<string> JavaPaths { get; }

        public static string PlayerName
        {
            get => SettingModel.Setting.PlayerName;
            set
            {
                SettingModel.Setting.PlayerName = value;
                SettingModel.Save();
            }
        }
    }
}
